<?php
/**
 * Created by PhpStorm.
 * User: liqiang
 * Date: 16-12-29
 * Time: 下午2:25
 */
namespace Inbound\Controller;

use Home\Controller\CommonController;
use Inbound\Service\TransportplanService;
use Inbound\Service\PublicInfoService;
use Inbound\Service\PublicPlugService;

//物流计划单管理模块
class TransportplanController extends CommonController
{
    //物流计划单列表(查询,导出,修改,标记发货,移除某个平台计划单)
    public function index()
    {
        $pubser = new \Inbound\Service\PublicInfoService();
        //$transport_plan_model = M('fba_transport_plan',NULL,"DB_FBAERP");
        //var_dump($transport_plan_model->where('id=1')->find());exit;
        $transportSer = D('Transportplan', 'Service');
        //获取参数
        $codetype  = I('get.codetype');
        $transcode  = I('get.transcode');
        $carrier_service = I('get.carrier_service');
        $creater    = PublicInfoService::get_user_id_by_name(I('get.creater'));
        $status     = I('get.status');
        $start_time = I('get.start_time');
        $end_time   = I('get.end_time');
        $page       = I('get.p', 1, 'int');
        //定义变量
        $param = array(
            'codetype'  => $codetype,
            'transcode'  => $transcode,
            'carrier_service' => $carrier_service,
            'creater'    => $creater,
            'status'     => (int)$status,
            'start_time' => $start_time,
            'end_time'   => $end_time
        );
        //var_dump ($param);exit;
        $datetype = I('get.datetype') ? I('get.datetype') : '';
        if (!empty($datetype)) {
            $param['datetype'] = $datetype;
        }
        if (I('get.exportall')=='导出全部') {
            $this->exportransplan($param);//导出全部物流计划
        } elseif (I('post.checked')=='导出选中') {
            $where['id'] = array(
                'in',
                $_POST['transplans']
            );
            $this->exportransplan($where);//导出选中物流计划
        } elseif (I('get.downloadSendData') == '仓储下载FBA待发货数据(默认为当天待发货数据)') {
            $option = array();
            $option['create_time_start'] = empty($start_time) ? date('Y-m-d') : $start_time;
            $option['create_time_end'] = empty($end_time) ? date('Y-m-d').' 23:59:59' : $end_time;
            $option['carrier_service_id'] = empty($carrier_service) ? '' : $carrier_service;
            $this->exportSendData($option);//下载FBA发货明细
        } elseif (I('post.checked')=='标记发货') {
            $where['id'] = array(
                'in',
                $_POST['transplans']
            );
            //var_dump($where);exit;
            $this->batchmarkshipped($where);//标记发货
        }elseif(I('get.downall')=='下载FBA物流计划单'){
            $this->exportransplanOther($param);//导出全部物流计划
        }
        $pagesize = 25;         //每页大小
        $limit    = $pagesize*($page-1).','.$pagesize;
        $transCnt = count($transportSer->getTransportplan($param));
        //获取分页信息
        $transresult = $transportSer->getTransportplan($param, $limit);
        //var_dump($transresult);exit;
        //实例化分页类 传入总记录数和每页显示的记录数(13)
        $Page = new \Think\Page($transCnt, $pagesize);
        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('first', '首页');
        $Page->setConfig('last', '末页');
        foreach($transresult as &$data){
            if ($data['status']==50) {
                $data['status'] = '待发货';
            } elseif ($data['status']==60) {
                $data['status'] = '已发货';
            } elseif ($data['status']==70) {
                $data['status'] = '已到货';
            } elseif ($data['status']==100) {
                $data['status'] = '已取消';
            }
        }
        $pubser          = new \Inbound\Service\PublicInfoService();
        $carrier_service = PublicInfoService::get_transport_way_array();
        $shiptoaddresses = PublicInfoService::get_ship_to_addresses_array();
        $this->assign('carrier_service', $carrier_service);
        $this->assign('shiptoaddresses', $shiptoaddresses);
        //分页显示输出
        $show = $Page->show();
        //分页内容
        $this->assign('transresult', $transresult);
        //搜索信息
        $this->assign('param', $param);
        //分页按钮
        $this->assign('Pager', $show);
        //当前页
        $this->assign('page', $page);
        //总页数
        $this->assign('pageSize', ceil($transCnt/$pagesize));
        //总记录数
        $this->assign('total', $transCnt);
        $this->display();
    }
    /**
     * 创建物流计划
     * @return
     */
    public function createTransPlan()
    {
        $transportSer = D('Transportplan', 'Service');
        //获取参数
        $site            = I('get.site_id');
        $carrier_service = I('get.carrier_service');
        //$status=I('get.status');
        $taxrebate  = I('get.taxrebate');
        $start_time = I('get.start_time');
        $end_time   = I('get.end_time');
        //定义变量
        $param    = array(
            'site_id'         => $site,
            'carrier_service' => $carrier_service,
            //'status'             => (int)$status,
            'taxrebate'       => $taxrebate,
            'start_time'      => $start_time,
            'end_time'        => $end_time
        );
        $datetype = I('get.datetype') ? I('get.datetype') : '';
        if (!empty($datetype)) {
            $param['datetype'] = $datetype;
        }
        array_filter($param);
        //var_dump($param);exit;
        if (I('post.createtransplan')=='创建物流计划单') {
            //var_dump($_POST);exit;
            $newtransplan = $transportSer->createtransplan($_POST['platplans']);
            //echo "<span>物流计划单：".$newtransplan."，创建成功!</span>";
            $this->editTransPlan($newtransplan);
            exit;
            /*$this->assign('newtransplan',$newtransplan);
            $this->assign('cretedplans',$_POST['platplans']);*/
        }
        $platplans = $transportSer->getPlatplans($param);
        $sitelist  = $this->getallsites();
        $this->assign('sitelist', $sitelist);
        $this->assign('platplans', $platplans);
        $pubser          = new \Inbound\Service\PublicInfoService();
        $carrier_service = PublicInfoService::get_transport_way_array();
        $shiptoaddresses = PublicInfoService::get_ship_to_addresses_array();
        $this->assign('shiptoaddresses', $shiptoaddresses);
        $this->assign('carrier_service', $carrier_service);
        $this->display('Transportplan/createTransPlan');
    }

    /**
     * 编辑New物流计划
     * @return
     */
    public function editNewTrans()
    {
        $platid       = I('get.platid');//I('get.platid') $_POST['platplans']
        $transportSer = D('Transportplan', 'Service');
        $newtransplan = $transportSer->createtransplan($platid);
        //var_dump ($id);exit;
        if ($newtransplan>0) {
            $param['id'] = $newtransplan;
            $trans       = D('Transportplan', 'Service');
            $transDetail = $trans->getTransplan($param);
            //var_dump ($transDetail);exit;
            $sitelist  = $this->getallsites();
            $this->assign('sitelist', $sitelist);
            $this->assign('transDetail', $transDetail[0]);
            //$carrier_service = $trans->getCarrierServiceList();
            $pubser          = new \Inbound\Service\PublicInfoService();
            $carrier_service = PublicInfoService::get_transport_way_array();
            $this->assign('carrier_service', $carrier_service);
            $this->assign('type', 1);
            C("LAYOUT_ON", false);
            $this->display('Transportplan/editTransPlan');
        } else {
            echo "<script>alert('平台计划单状态错误，创建失败，请重新创建.');parent.location.reload(); </script>";
            exit;
        }
    }

    /**
     *编辑、更新或修改（无用）
     * @return
     */
    public function update()
    {
        return TRUE;
    }

    /**
     * 获取平台计划单详情
     * @return
     */
    public function getPlatPlan()
    {
        //die('ok');
        //$transport_plan_model = M('fba_transport_plan',NULL,"DB_FBAERP");
        //var_dump($transport_plan_model->where('id=1')->find());exit;
        $transportSer = D('Transportplan', 'Service');
        //获取参数
        $transcode  = I('get.transcode') ? I('get.transcode') : '';
        $creater    = I('get.creater') ? I('get.creater') : '';
        $status     = I('get.status') ? I('get.status') : 0;
        $start_time = I('get.start_time') ? I('get.start_time') : '';
        $end_time   = I('get.end_time') ? I('get.end_time') : '';
        $page       = I('get.p', 1, 'int');
        //定义变量
        $param    = array(
            'transcode'  => $transcode,
            'creater'    => $creater,
            'status'     => (int)$status,
            'start_time' => $start_time,
            'end_time'   => $end_time
        );
        $datetype = I('get.datetype') ? I('get.datetype') : '';
        if (!empty($datetype)) {
            $param['datetype'] = $datetype;
        }
        //var_dump($param);exit;
        $platplans       = $transportSer->getPlatplans($param);
        $carrier_service = $transportSer->getCarrierServiceList();
        $this->assign('platplans', $platplans);
        $this->assign('carrier_service', $carrier_service);
        //$this->assign('param',$param);
        $this->display('Transportplan/createTransPlan');
    }

    /**
     * 获取装箱详情（无用）
     * @return
     */
    public function get_package_detail()
    {
        return TRUE;
    }

    /**
     * 修改物流计划详情
     * @return
     */
    public function editTransPlan($id = 0)
    {
        if ($id==0) {
            $id = I('get.id');
        }
        //var_dump ($id);exit;
        if ($id) {
            $param['id'] = $id;
            $trans       = D('Transportplan', 'Service');
            $transDetail = $trans->getTransplan($param);
            //var_dump ($transDetail);exit;
            $sitelist  = $this->getallsites();
            $this->assign('sitelist', $sitelist);
            $this->assign('transDetail', $transDetail[0]);
            //$carrier_service = $trans->getCarrierServiceList();
            $pubser          = new \Inbound\Service\PublicInfoService();
            $carrier_service = PublicInfoService::get_transport_way_array();
            $this->assign('carrier_service', $carrier_service);
        }
        C("LAYOUT_ON", false);
        $this->assign('type', 2);
        $this->display('Transportplan/editTransPlan');
    }

    /**
     * 修改物流计划单处理
     */
    public function ajaxEditTrans()
    {
        //获取参数
        $transid                = I('post.id');
        $status                 = I('post.status');
        $transport_plan_code    = I('post.transport_plan_code');
        $certificate_code       = I('post.certificate_code');
        $carrier_service_id     = I('post.carrier_service_id');
        $delivery_proxy         = I('post.delivery_proxy');
        $ori_driver_name         = I('post.ori_driver_name');
        $ori_driver_tel         = I('post.ori_driver_tel');
        $ori_license_plate_num         = I('post.ori_license_plate_num');
        $ori_tracking_num         = I('post.ori_tracking_num');
        $certificate_code         = I('post.certificate_code');
        $ori_seal_num         = I('post.ori_seal_num');
        $transport_supplier_id  = I('post.transport_supplier_id');
        $expected_pickup_time   = I('post.expected_pickup_time');
        $pickup_op_user_id      = I('post.pickup_op_user_id');
        $pickup_op_time         = I('post.pickup_op_time');
        $arrive_port_date       = I('post.arrive_port_date');
        $take_off_date          = I('post.take_off_date');
        $arrive_time            = I('post.arrive_time');
        $customs_clearance_date = I('post.customs_clearance_date');
        $delivery_date          = I('post.delivery_date');
        $destination_site_id          = I('post.destination_site_id');
        $clearance_port          = I('post.clearance_port');
        //定义变量
        $trans   = D('Transportplan', 'Service');
        $postArr = array(
            'id'                     => $transid,
            'transport_plan_code'    => $transport_plan_code,
            'status'                 => $status,
            'certificate_code'       => $certificate_code,
            'carrier_service_id'     => $carrier_service_id,
            'delivery_proxy'         => $delivery_proxy,
            'ori_driver_name'         => $ori_driver_name,
            'ori_driver_tel'         => $ori_driver_tel,
            'ori_license_plate_num'         => $ori_license_plate_num,
            'ori_tracking_num'         => $ori_tracking_num,
            'certificate_code'         => $certificate_code,
            'ori_seal_num'         => $ori_seal_num,
            'transport_supplier_id'  => $transport_supplier_id,
            'expected_pickup_time'   => $expected_pickup_time,
            'pickup_op_user_id'      => $pickup_op_user_id,
            'pickup_op_time'         => $pickup_op_time,
            'arrive_port_date'       => $arrive_port_date,
            'take_off_date'          => $take_off_date,
            'arrive_time'            => $arrive_time,
            'customs_clearance_date' => $customs_clearance_date,
            'destination_site_id' => $destination_site_id,
            'clearance_port' => $clearance_port,
            'delivery_date'          => $delivery_date
        );
        //var_dump ($postArr);exit;
        //校验参数
        /*if(empty($pickingtime)){      //提货时间为空
            $ret = '提货时间为必填项';
            $this->ajaxReturn($ret);
        }*/
        $tranModel = M('fba_transport_plan',NULL,'DB_FBAERP');
        $code = $tranModel->where("id = $transid")->find();
        $res = $trans->editTrans($postArr);
        if ($res!==false) {
            $ret = '修改成功';
            if($code['destination_site_id']==NULL){
                //推到关务的接口
                D('Api/Amazon/Client','Controller')->pushTransportInfo($transid);
            }
        } else {
            $ret = '修改失败';
        }
        //$this->ajaxReturn($ret);
        echo "<script>alert('".$ret."');parent.location.reload(); </script>";
    }

    /**
     * 标记发货
     */
    public function markship()
    {
        C("LAYOUT_ON", false);
        $id = I('get.id');
        //var_dump ($id);exit;
        if ($id) {
            $param['id'] = $id;
            $trans       = D('Transportplan', 'Service');
            $transDetail = $trans->getTransplan($param);
            //var_dump ($transDetail);exit;
            $this->assign('transDetail', $transDetail[0]);
        }
        $pubser          = new \Inbound\Service\PublicInfoService();
        $carrier_service = PublicInfoService::get_transport_way_array();
        $this->assign('carrier_service', $carrier_service);
        $this->display('Transportplan/markship');
    }

    /**
     * 标记发货处理
     */
    public function ajaxMarkShip()
    {
        //获取参数
        $transid               = I('post.id');
        $transport_plan_code   = I('post.transport_plan_code');
        $certificate_code      = I('post.certificate_code');
        $carrier_service_id    = I('post.carrier_service_id');
        $delivery_proxy        = I('post.delivery_proxy');
        $transport_supplier_id = I('post.transport_supplier_id');
        $expected_pickup_time  = I('post.expected_pickup_time');
        $ret = '';
        //定义变量
        $trans   = D('Transportplan', 'Service');
        $postArr = array(
            'id'                    => $transid,
            'status'                => 60,
            'certificate_code'      => $certificate_code,
            'carrier_service_id'    => $carrier_service_id,
            'delivery_proxy'        => $delivery_proxy,
            'transport_supplier_id' => $transport_supplier_id,
            'expected_pickup_time'  => $expected_pickup_time,
            'pickup_op_time'        => date('Y-m-d H:i:s', time()),
            'pickup_time'           => date('Y-m-d H:i:s', time())
        );
        $res     = $trans->editTrans($postArr);
        if ($res['status']==200) {
            $ret .= '修改成功';
        } else {
            $ret .= $res['msg'];
        }
        $this->ajaxReturn($ret);
    }

    /**
     * 导出物流计划
     * @return
     */
    public function exportransplan(&$condition)
    {
        //数据量大,达到40万条，取消执行时间限制
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $transportSer = D('Transportplan', 'Service');
        $data_arr     = $transportSer->getTransportplan($condition);
        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $filename = "物流计划".date('Y-m-d', time());
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename.csv");
        ob_end_clean();//关闭缓存
        //输出表头
        $table_head = array(
            '状态',
            '物流计划单号',
            '合同号',
            '发票号',
            '入仓号/柜号',
            '承运商服务',
            '创建人',
            '创建时间',
            '司机姓名（电话）',
            '车牌号',
            '提单号/快递单号',
            '封条号',
            '预计提货时间',
            '发货人',
            '发货时间',
            '到港时间',
            '起飞时间',
            '到目的地时间',
            '清关时间',
            '派送时间',
            'Shipmentid',
            /*'SKU',
            '虚拟SKU',
            '产品名称',
            '储位',
            '数量',
            '是否退税',
            '销售员',
            '采购员'
            '状态',*/
            '所属需求批次',
            '账号名',
            '站点',
            '承运商服务',
            '中转仓库名',
            '亚马逊目的仓地址',
            '要求到货时间',
            '包裹数',
            '重量',
            '体积'
        );
        fputcsv($output, $table_head);
        foreach($data_arr as $val){//$data_arr是数据集，二维数组




            fputcsv($output, array_values($val));
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }
    /**
     * 导出物流计划
     * @return
     */
    public function exportransplanOther(&$condition)
    {
        //        $transportSer = D('Transportplan', 'Service');
        //        $data_arr     = $transportSer->getTransportplanOther($condition);
        //        print_r($data_arr);
        //        exit;
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $filename = "FBA物流计划单".date('Y-m-d', time());
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename.csv");
        ob_end_clean();//关闭缓存
        $transportSer = D('Transportplan', 'Service');
        $data_arr     = $transportSer->getTransportplanOther($condition);
        $limit = 1000;
        $calc  = 0;
        //输出表头
        $table_head = array(
            '物流计划单号',
            '合同号',
            '发票号',
            '入仓号/柜号',
            '封条号',
            '提单号/快递单号',
            '承运商服务',
            'ShipmentId',
            'SKU',
            '采购订单号',
            '采购员',
            '采购名称',
            '报关品名',
            '英文品名',
            '海关编码',
            '退税率',
            '品牌',
            '型号',
            '申报要素',
            'Quantity 数量(PCS)',
            '含税采购单价',
            '含税采购总价',
            '净重KG(单个SKU)',
            '毛重KG（GW/PCS,包装后的单个SKU）',
            '体积CM3（包装后的单个SKU体积）',
            '采购主体',
            '供货商名称',
            '是否退税',
            '箱号',
            '托盘号',
            '销售账号名称',
            '站点',
            '起运地',
            '目的地',
            '亚马逊配送中心标识',
            'sellerSKU',
            'FBA单据生成时间',
            '是否单独发货',
            '要求到货时间',
            '销售员',
            '备货需求计划状态',
            '物流渠道',
            '备货需求创建人',
            '备货需求创建时间',
            '销售确认人',
            '销售确认时间',
            '物流预审人',
            '物流预审时间',
            '备注',
            "货物等级",
            "海外监管条件",
        );
        foreach($table_head as $v){
            $tit[] = iconv('UTF-8','GB2312//IGNORE',$v);
        }
        fputcsv($output, $tit);
        foreach($data_arr AS $key => $j){
            $down = array(
                $j['transport_plan_code'],
                $j['contract_no'],
                $j['invoice_code'],
                $j['certificate_code'],
                $j['ori_seal_num'],
                $j['ori_tracking_num'],
                $j['carrier_service_id'],
                $j['shipmentid'],
                $j['sku'],
                $j['purchaseorders_id'],
                $j['purchase_id'],
                $j['sku_name'],
                $j['item'],
                $j['en_item'],
                $j['hs_code'],
                $j['export_tax'],
                $j['logo'],
                $j['type_number'],
                $j['report_elements'],
                $j['quantity'],
                $j['single_price'],
                $j['money'],
                $j['weight'],
                $j['asweight'],
                $j['volume'],
                $j['enterprise_dominant_other'],
                $j['supplier'],
                $j['export_tax_rebate'],
                $j['box_code'],
                '',
                $j['need_account_name'],
                $j['need_site_id'],
                $j['ship_from_address_id'],
                $j['ship_to_address_id'],
                $j['destination_fullfillment_center_id'],
                $j['seller_sku'],
                $j['create_time'],
                $j['need_single_ship'],
                $j['need_claim_arrive_time'],
                $j['need_seller_id'],
                $j['need_status'],
                $j['transport_carrier_service_id'],
                $j['need_create_user_id'],
                $j['need_create_time'],
                $j['need_seller_check_user_id'],
                $j['need_seller_check_time'],
                $j['need_logistic_check_user_id'],
                $j['need_logistic_check_time'],
                $j['need_remark'],
                $j['need_cargo_grade'],
                $j['overseas_supervision'],
            );
            $calc++;
            if($limit==$calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($down as $t){
                $tarr[] = iconv('UTF-8','GB2312//IGNORE',trim($t));
            }
            fputcsv($output,$tarr);
            unset($tarr);
        }
        fclose($output) or die("can't close php://output");
        exit;
    }

    /**
     * 物流计划单批量标记发货
     * @return
     */
    public function batchmarkshipped(&$condition)
    {
        $transportSer = D('Transportplan', 'Service');
        $data_arr     = $transportSer->update($condition);
    }

    /**
     * 批量物流追踪
     */
    public function batchedittrans()
    {
        $trans = D('Transportplan', 'Service');
        if ($_POST) {
            $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
            if (!PublicPlugService::$flag) {                                            //选择了上传文件,状态返回false
                if (count($sheetData)>=2) {
                    $datas = array();
                    $str   = '';
                    $i     = 0;
                    foreach ($sheetData as $k => $v) {
                        if ($k>=2) {
                            //$v = $this->trim_array($v);                                            //过滤元素的空格
                            $data    = array(
                                //'transport_plan_code'           => mysql_escape_mimic($v['A']),//物流计划单号
                                //'status'                  => mysql_escape_mimic($v['B']),      //物流状态
                                'certificate_code'       => mysql_escape_mimic($v['C']),
                                //物流追踪码
                                //'carrier_service'              => mysql_escape_mimic($v['D']),  //承运商服务
                                'delivery_proxy'         => mysql_escape_mimic($v['E']),
                                //目的国派送代理
                                'expected_pickup_time'   => mysql_escape_mimic($v['F']),
                                //预计提货时间
                                'arrive_port_date'       => mysql_escape_mimic($v['G']),
                                //到港时间
                                'take_off_date'          => mysql_escape_mimic($v['H']),
                                //起飞时间
                                'arrive_time'            => mysql_escape_mimic($v['I']),
                                //到目的地时间
                                'customs_clearance_date' => mysql_escape_mimic($v['J']),
                                //清关时间
                                'delivery_date'          => mysql_escape_mimic($v['K'])
                                //派送时间
                            );
                            $mtrans  = M('fba_transport_plan', null, 'DB_FBAERP');
                            $transid = $mtrans->where(array('transport_plan_code' => trim($v['A'])))
                                ->field('id,status')
                                ->select();
                            if (!$transid[0]['id']) {
                                $str .= '第'.$k.'行,'.$v['A'].',物流计划单号不存在，请检查.</br>';
                                $i++;
                                continue;
                            } else {
                                $data['id'] = $transid[0]['id'];
                            }
                            if (!$transid[0]['id']) {
                                $str .= '第'.$k.'行,'.$v['A'].',物流计划单号不存在，请检查.</br>';
                                $i++;
                                continue;
                            }
                            if ($transid[0]['status']==50) {
                                $str .= '第'.$k.'行,'.$v['A'].',物流计划单号未发货，请检查.</br>';
                                $i++;
                                continue;
                            } elseif (in_array($v['B'], array('已到货', '已完成'))) {
                                $data['status'] = 70;
                            }
                            if (!empty($v['D'])) {
                                $pubser                     = new \Inbound\Service\PublicInfoService();
                                $carrier_service            = PublicInfoService::get_transport_way_array();
                                $carrier_service            = array_flip($carrier_service);
                                $data['carrier_service_id'] = $carrier_service[trim($v['D'])];
                            }
                            $res = $trans->editTrans($data);
                            if (!$res) {
                                $str .= '第'.$k.'行,'.$v['A'].',更新失败，请检查.</br>';
                                $i++;
                            }
                            $datas[] = $data;
                        }
                    }
                    $str .= '成功更新'.(count($datas)-$i).'条,失败'.$i.'条';
                    $this->assign('result', $str);
                } else {
                    $this->assign("result", "文件内容为空");
                }
            } else {
                $this->assign("result", "请选择上传文件");
            }
        }
        $this->display();
    }

    /**
     * 从物流计划单中移除单个平台计划单
     * @return
     */
    public function delplat()
    {
        $transportSer        = D('Transportplan', 'Service');
        $param['shipmentid'] = I('post.id');
        $result              = $transportSer->delplat($param);
        if ($result) {
            $ret = '移除成功';
            $this->ajaxReturn($ret);
        }
    }

    /**
     * 取消物流计划单
     * @return
     */
    public function cancelTransPlan()
    {
        $transportSer = D('Transportplan', 'Service');
        $param['id']  = I('post.id');
        $result       = $transportSer->cancelTransPlan($param);
        if ($result) {
            $ret = '取消成功';
            $this->ajaxReturn($ret);
        }
    }

    /**
     * 获取站点列表
     * @return
     */
    public function getallsites()
    {
        $getsites = new \Api\Model\Amazon\SitesModel();
        $data_arr = $getsites->getSites();
        return $data_arr;
    }
    public function getTest(){
        $data['skuParam'] = array('AM177703');
        $handle = curl_init();
        print_r($handle);
        //$url = 'http://192.168.5.6:703/commonapi/newerpapi/getHistoryPuInfo';
        $url = '';
        curl_setopt($handle,CURLOPT_URL,$url);
        curl_setopt($handle,CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($handle,CURLOPT_USERAGENT,'Fbawarehouse API/1.0');
        curl_setopt($handle,CURLOPT_CONNECTTIMEOUT,60);
        curl_setopt($handle,CURLOPT_TIMEOUT,90);
        curl_setopt($handle,CURLOPT_MAXREDIRS,3);
        curl_setopt($handle,CURLOPT_POST,TRUE);
        curl_setopt($handle,CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($handle,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
        curl_setopt($handle,CURLOPT_HEADER,FALSE);    //不返回头信息
        $response = curl_exec($handle);
        print_r($response);exit;
        if(curl_errno($handle)) {
            $re          = new \stdClass();
            $re->code    = 100;
            $re->message = '连接主机'.$url.'时发生错误: '.curl_error($handle)."<br/>";
            curl_close($handle);
            return json_encode($re);
        }
        curl_close($handle);
        $jieArr=json_decode($response, true);
        print_r($jieArr); 
    }
    /**
     * 描述: 出口退税物流统计表
     * 作者: kelvin
     */
    public function exportRebateStatistics() {
        if($_GET){
            $shipStatus = ' ';
            $tranTime = '';
            $transport_plan_code = '';
            if(I('get.tranId')){
                $tranId = $this->trimAll(I('get.tranId'));
                $tranIds = implode("','",explode(",",$tranId));
                $transport_plan_code .= " AND `transport_plan_code` IN ('".$tranIds."')";
            }

            if(I('get.status')){
                $shipStatus = ' AND fb.status = '.I('get.status');
            }
            if(I('get.time_from')){
                $tranTime .= " AND pickup_op_time >= '".I('get.time_from')."'";
            }
            if (I('get.time_to')){
                $tranTime .= " AND pickup_op_time <= '".I('get.time_to')."'";
            }

            $sqli = '';
            if($transport_plan_code != '' || $tranTime != '') {
                $sqli = " AND fb.transport_plan_id IN(
                    SELECT
                      id
                    FROM
                      `fba_transport_plan`
                    WHERE 1
                      ".$transport_plan_code."
                      ".$tranTime."
                  )";
            }

            $Model =  M('',' ','fbawarehouse'); // 实例化一个model对象 没有对应任何数据表
            $result = $Model->query("SELECT
                  a.account_name,
                  a.shipmentid,
                  a.shorthand_code,
                  a.shipmentidStatus,
                  a.total_package,
                  a.total_weight,
                  a.total_capacity,
                  a.shipmentidCreateMan,
                  a.shipmentidRemark,
                  a.create_time,
                  a.sku,
                  a.seller_sku,
                  a.sku_name,
                  a.quantity AS shipmentidQty,
                  w.id AS 'wid',
                  w.warehouse_date,
                  wd.quantity AS wareQty,
                  a.export_tax_rebate,
                  a.enterprise_dominant,
                  w.purchaseorders_id,
                  su.name AS suName,
                  pu.purchase_id AS puMan,
                  pd.single_price *(1 + pd.`real_tax_rate`) AS 'single_price',
                  pd.`quantity` AS puQty,
                  sst.item AS 'item',
                  sst.sku_unit,
                  sst.rate AS exportRate,
                  sst.`report_elements`,
                  sst.hs_code
                FROM
                  (
                  SELECT
                    fb.`account_name`,
                    fb.shipmentid,
                    fb.status AS shipmentidStatus,
                    sites.shorthand_code,
                    fb.`total_package`,
                    fb.`total_weight`,
                    fb.`total_capacity`,
                    fb.`create_user_id` AS shipmentidCreateMan,
                    fb.`create_time`,
                    fb.`remark` AS shipmentidRemark,
                    fspd.`sku`,
                    fspd.`seller_sku`,
                    fspd.`sku_name`,
                    fspd.`quantity`,
                    fspd.`export_tax_rebate`,
                    fspd.`enterprise_dominant`,
                    fspd.`hs_code`,
                    fspd.deliveryorders_id
                  FROM
                    `fba_inbound_shipment_plan_detail` AS fspd
                  LEFT JOIN
                    `fba_inbound_shipment_plan` fb
                  ON
                    fb.id = fspd.`inbound_shipment_plan_id`
                  LEFT JOIN
                    amazonorder_sites AS sites
                  ON
                    sites.id = fb.site_id
                  WHERE
                    fspd.`enterprise_dominant` != 1 ".$shipStatus . $sqli ."
                ) a
                LEFT JOIN
                  wms_warehouse_deliveryorders AS wd
                ON
                  wd.deliveryorders_id = a.deliveryorders_id
                LEFT JOIN
                  wms_warehouseorders AS w
                ON
                  w.id = wd.warehouseorders_id
                LEFT JOIN
                  wms_purchaseorder_details AS pd
                ON
                  (
                    pd.purchaseorder_id = w.purchaseorders_id AND pd.sku = w.sku
                  )
                LEFT JOIN
                  wms_purchaseorders AS pu
                ON
                  pu.id = pd.purchaseorder_id
                LEFT JOIN
                  skusystem_suppliers AS su
                ON
                  su.id = w.supplier_id
                LEFT JOIN
                  skusystem_sku_taxrate AS sst
                ON
                  sst.sku = a.sku");
            if(count($result)==0){
                echo '<script>alert("没有数据");history.go(-1)</script>';die;
            }
            $admin = PublicInfoService::get_user_name_and_id();
            $status = PublicInfoService::get_inbound_status();
            $emptyPuIdSkus = array();
            foreach($result as $k =>&$v){
                $v['shipmentidCreateMan'] = $admin[$v['shipmentidCreateMan']];
                $v['puMan'] = $admin[$v['puMan']];
                $v['shipmentidStatus'] = $status[$v['shipmentidStatus']];
                $v['enterprise_dominant'] = PublicInfoService::getCompanyName($v['enterprise_dominant']);
                $v['export_tax_rebate'] = $v['export_tax_rebate']==1?'是':'否';

                empty($v['purchaseorders_id']) && $emptyPuIdSkus[] = $v['sku'];

            }
            if($_GET['shuDown'] && count($emptyPuIdSkus)!=0){

                $data['skuParam'] = array_unique($emptyPuIdSkus);
                $handle = curl_init();
                $url = 'http://192.168.5.6:703/commonapi/newerpapi/getHistoryPuInfo';
                curl_setopt($handle,CURLOPT_URL,$url);
                curl_setopt($handle,CURLOPT_RETURNTRANSFER,TRUE);
                curl_setopt($handle,CURLOPT_USERAGENT,'NewerpAPI/1.0');
                curl_setopt($handle,CURLOPT_CONNECTTIMEOUT,60);
                curl_setopt($handle,CURLOPT_TIMEOUT,90);
                curl_setopt($handle,CURLOPT_MAXREDIRS,3);
                curl_setopt($handle,CURLOPT_POST,TRUE);
                curl_setopt($handle,CURLOPT_POSTFIELDS,http_build_query($data));
                curl_setopt($handle,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
                curl_setopt($handle,CURLOPT_HEADER,FALSE);    //不返回头信息

                $response = curl_exec($handle);
                if(curl_errno($handle)) {
                    $re          = new \stdClass();
                    $re->code    = 100;
                    $re->message = '连接主机'.$url.'时发生错误: '.curl_error($handle)."<br/>";
                    curl_close($handle);
                    return json_encode($re);
                }

                curl_close($handle);
                $skuData = json_decode($response, true);
                $output1 = fopen('php://output', 'w') or die("can't open php://output");
                //告诉浏览器这个是一个csv文件
                $filename1 = "无采购单号二次追踪表格".date('Ymd', time());
                header("Content-Type: application/csv");
                header("Content-Disposition: attachment; filename=$filename1.csv");
                ob_end_clean();//关闭缓存
                $csvHead = array(
                    '采购单号',
                    '采购日期',
                    '采购员',
                    '是否出口退税',
                    '主体',
                    'sku编码',
                    '含税单价',
                    '数量',
                    'sku总额',
                    '税率'
                );
                fputcsv($output1, $csvHead);
                foreach($skuData['data'] as $key=>$val){//$data_arr是数据集，二维数组
                    $key == 'noTrackPuIdSku' || fputcsv($output1, array_values($val));
                }

                if(!empty($skuData['data']['noTrackPuIdSku'])) {
                    fputcsv($output1, array_values(array('以下SKU无法追踪到采购订单：')));
                    foreach($skuData['data']['noTrackPuIdSku'] as $noTrackSku) {
                        fputcsv($output1, array($noTrackSku));
                    }
                }
                //关闭文件句柄
                fclose($output1) or die("can't close php://output");
                exit;
            }
            $output = fopen('php://output', 'w') or die("can't open php://output");
            //告诉浏览器这个是一个csv文件
            $filename = "出口退税物流统计表".date('Ymd', time());
            header("Content-Type: application/csv");
            header("Content-Disposition: attachment; filename=$filename.csv");
            ob_end_clean();//关闭缓存
            //输出表头
            $table_head = array(
                '店铺帐号名',
                'shipmentid',
                '站点',
                'shipmentid状态',
                'shipmentid总箱数',
                'shipmentid总重量',
                'shipmentid总体积',
                'Shipmentid生成人',
                'Shipmentid销售备注',
                'Shipmentid生成时间',
                'SKU编码',
                '平台sku',
                '采购名称',
                '数量',
                '入库单id',
                '入库日期',
                '入库数量',
                '是否出口退税',
                '主体',
                '采购单号',
                '供应商名称',
                '采购员',
                '含税单价',
                '采购数量',
                '报关品名',
                '报关单位',
                '退税率',
                '申报要素',
                '报关编码'
            );
            fputcsv($output, $table_head);
            foreach($result as $val){//$data_arr是数据集，二维数组
                fputcsv($output, array_values($val));
            }
            //关闭文件句柄
            fclose($output) or die("can't close php://output");
            exit;


        }
        $this->display();
    }
    /**
     * 描述: 去除所有空格
     * 作者: kelvin
     */
    public function trimAll($str) {
        $find = array(" ","　","\t","\n","\r");
        $replace = array("","","","","");
        return str_replace($find,$replace,$str);
    }
    /**
     * 描述: FBA头程分摊计算报表
     * 作者: kelvin
     */
    public function fbaHead() {
        if($_POST){
            $this->uploadFile();die;
        }
        if($_GET['fileName']){
            PublicPlugService::download_templet_xlsx();die;
        }

        $this->display();
    }
    /**
     * 上传
     */
    public function uploadFile()
    {
        $tranService = D('Inbound/Transportplan','Service');
        $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
        if(!$sheetData) {
            echo "<script>alert('文件内容解析有误，请检查文件内容');history.go(-1)</script>";
            exit;
        }
        if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
            if(count($sheetData)>=2){
                $check_data = $tranService->check_upload_data($sheetData); // 检查导入的备货需求数据合法性
                if(!$check_data['status']){
                    echo "<script>alert('".$check_data['message']."');history.go(-1)</script>";
                    exit;
                }
                $tranService->upload_platform($sheetData);//最后解析数据,验证,更新数据库
            }else{
                echo "<script>alert('文件内容为空');history.go(-1)</script>";die;
            }
        }else{
            echo '<script>alert("请选择上传文件");history.go(-1)</script>';die;
        }
    }
    /**
     * 物流交接单模板下载
     * 作者:kelvin
     */
    public function tranDownload()
    {
        PublicPlugService::download_templet_xlsx();
    }

    /**
     *  物流交接单模板上传下载
     *  作者:kelvin
     * */
    public function upload_site()
    {
        $tranService = D('Transportplan', 'Service');
        $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
        if(!$sheetData) {
            echo "<script>alert('文件内容解析有误，请检查文件内容');history.go(-1)</script>";
            exit;
        }
        if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
            if(count($sheetData)>=2){
                $result = '';
                $data = array();
                $site  =  M('amazonorder_sites',' ','DB_FBAERP')->where('is_used = 1')->getField('shorthand_code,id');
                foreach ($sheetData as $c =>$v){
                    if($c>1){
                        if(trim($v['A'])==''){
                            $result .= '第'.$c.'行为空\\n';continue;
                        }
                        if(!in_array(strtoupper(trim($v['A'])),array_keys($site))){
                            $result .= '第'.$c.'行站点'.trim($v['A']).'不存在\\n';continue;
                        }
                        $data[] = $site[$v['A']];
                    }
                }
                if($result!=''){
                    echo "<script>alert('".$result."');window.location.href = 'createTransPlan'</script>";die;
                }else{
                    $tranService->upload_site(array_unique($data));
                }

            }else{
                echo "<script>alert('文件内容为空');history.go(-1)</script>";die;
            }
        }else{
            echo '<script>alert("请选择上传文件");history.go(-1)</script>';die;
        }
    }

    /**
     * 导出FBA发货数据
     * @return
     */
    public function exportSendData(&$condition) {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $carrierServiceStr = empty($condition['carrier_service_id']) ? '' : ' AND ftp.carrier_service_id=' . $condition['carrier_service_id'];
        $createStartTime = empty($condition['create_time_start']) ? '' : ' AND ftp.create_time >= \'' . $condition['create_time_start'] . '\'';
        $createEndTime = empty($condition['create_time_end']) ? '' : ' AND ftp.create_time <= \'' . $condition['create_time_end'] . '\'';

        $data = M('fba_inbound_shipment_plan',' ','fbawarehouse')
            ->join('LEFT JOIN fba_transport_plan ftp on ftp.id = fba_inbound_shipment_plan.transport_plan_id')
            ->join('LEFT JOIN fba_carrier_service cs on cs.id = ftp.carrier_service_id')
            ->join('LEFT JOIN fba_carrier c on c.id = cs.carrier_id')
            ->join('LEFT JOIN amazonadmin.ea_admin a on a.id = fba_inbound_shipment_plan.create_user_id')
            ->where('1' . $createStartTime . $createEndTime . ' AND fba_inbound_shipment_plan.status = 50' . $carrierServiceStr)
            ->field("fba_inbound_shipment_plan.shipmentid,a.remark,c.name,cs.service_name,total_package,total_weight,total_capacity,ftp.transport_plan_code,ftp.create_time")
            ->select();
        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $filename = "下载FBA发货明细".date('Y-m-d', time());
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename.csv");
        ob_end_clean();//关闭缓存
        //输出表头
        $table_head = array(
            'shipmentid',
            '销售员',
            '承运商',
            '服务',
            '总箱数',
            '总重量',
            '总体积',
            '物流计划单编码',
            '物流计划时间'
        );
        fputcsv($output, $table_head);
        foreach($data as $val){//$data_arr是数据集，二维数组
            fputcsv($output, array_values($val));
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }
}